import { PlusOutlined } from '@ant-design/icons';
import { Form, Table, ConfigProvider, message, Popconfirm } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

import { GetModelListModels, AppsData } from '@/common/types';
import { Input, RequiredLabel, Button } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import ModalsBoxContent from '@/components/modals/ModalsBoxContent';
import Tip from '@/components/tip/Tip';
import useModal from '@/hooks/use-modal/useModal';

import './index.scss';

const index = forwardRef(
  (
    { modelData, updateModel, onCancel, onSubmit, okText, title, onClose, ...props }: Props,
    ref,
  ) => {
    const modals = useModal('close');

    const [tablesValue, setTablesValue] = useState<AppsData[]>([]);

    const [verticalLoading, setVerticalLoading] = useState(false);

    const [form] = Form.useForm();

    const [selectValue, setSelectValue] = useState<GetModelListModels>();

    const [testStatus, setTestStatus] = useState<boolean>(false);

    const columns = [
      {
        title: (
          <span className="flex items-center gap-1 !text-sm !font-normal text-text-4">
            <span>工具名称</span>
            <span className="ml-1 text-error">*</span>
            <Tip className="text-[16px] text-text-3" title="工具名称将在MCP客户端中显示" />
          </span>
        ),
        dataIndex: 'toolName',
        key: 'toolName',
        render: (_, record: AppsData) => (
          <Input
            required
            type="text"
            value={record.toolName}
            onChange={(e) => {
              setTablesValue((prev) => {
                return prev.map((item) => {
                  if (item.appId === record.appId) {
                    return {
                      ...item,
                      toolName: e.target.value,
                    };
                  }
                  return item;
                });
              });
            }}
          />
        ),
      },
      {
        title: <span className="!text-sm !font-normal text-text-4">应用名称</span>,
        dataIndex: 'appName',
        key: 'appName',
      },
      {
        title: (
          <span className="!text-sm !font-normal text-text-4">
            应用描述
            <span className="ml-1 text-error">*</span>
          </span>
        ),
        dataIndex: 'description',
        key: 'description',
        render: (_, record: AppsData) => (
          <Input
            type="text"
            value={record.description}
            onChange={(e) => {
              setTablesValue((prev) => {
                return prev.map((item) => {
                  if (item.appId === record.appId) {
                    return {
                      ...item,
                      description: e.target.value,
                    };
                  }
                  return item;
                });
              });
            }}
          />
        ),
      },
      {
        title: '',
        width: '15%',
        dataIndex: 'actions',
        key: 'actions',
        render: (_, record: AppsData) => (
          <div>
            <Popconfirm
              placement="topLeft"
              title="你确定删除吗？"
              onConfirm={() => {
                deleteItem(record.appId);
              }}
              okText="Yes"
              cancelText="No"
            >
              <Button type="text">
                <span className="flex items-center text-[#30343D]">
                  <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                </span>
              </Button>
            </Popconfirm>
          </div>
        ),
      },
    ];

    const deleteItem = async (id: string) => {
      setTablesValue((prev) => {
        return prev.filter((item) => item.appId !== id);
      });
      message.success('删除成功');
    };

    useImperativeHandle(ref, () => ({
      setTablesValue,
    }));

    useEffect(() => {
      setTablesValue(modelData?.apps || []);
      form.setFieldsValue({
        name: modelData?.name,
      });
    }, [modelData, props.open]);

    const handleApiVerify = (value: any) => {
      for (const item of tablesValue) {
        if (!item.appId || !item.toolName || !item.appName || !item.description) {
          message.error('工具名称、描述不能为空，请输入后再次点击确认');
          return;
        }
      }

      onSubmit({
        ...value,
        id: modelData?.id,
        apps: tablesValue,
      });
    };

    const init = () => {
      setVerticalLoading(false);
      onCancel();
    };

    return (
      <Modals
        title="创建MCP服务"
        onOk={form.submit}
        onCancel={init}
        {...props}
        width={720}
        confirmLoading={verticalLoading}
        okText="确认"
        onClose={onClose}
        modelContentClassName="!mr-0 !pr-0"
        footerOkDisabled={tablesValue.length === 0}
        destroyOnHidden
      >
        <Form layout="vertical" className="form !mr-6" form={form} onFinish={handleApiVerify}>
          <Form.Item
            label={<RequiredLabel className="text-text-4">服务名称</RequiredLabel>}
            rules={[
              { required: true, message: '请输入服务名称!' },
              { max: 20, message: `上限字数为20个` },
              {
                validator: (_, value) =>
                  value && value.trim() !== ''
                    ? Promise.resolve()
                    : Promise.reject(new Error('服务名称不能全为空格!')),
              },
            ]}
            name="name"
            required={false}
          >
            <Input maxLength={20} showCount />
          </Form.Item>
        </Form>

        <div className="mb-2 mr-6 flex items-center justify-between">
          <div className="text-text-4">应用列表({tablesValue.length})</div>
          {tablesValue.length > 0 && (
            <div>
              <Button
                type="text"
                icon={<PlusOutlined />}
                onClick={() => {
                  const value = {
                    ...form.getFieldsValue(),
                    apps: tablesValue,
                    id: modelData?.id,
                  };
                  updateModel(value);
                }}
              >
                添加应用
              </Button>
            </div>
          )}
        </div>

        {tablesValue.length === 0 ? (
          <div
            className="mr-6 flex h-[94px] cursor-pointer flex-col items-center justify-center gap-1 rounded-lg bg-fill-1 text-[#474C5F]"
            style={{
              width: 'calc(100% - 24px)',
            }}
            onClick={() => {
              const value = {
                ...form.getFieldsValue(),
                apps: tablesValue,
                id: modelData?.id,
              };
              updateModel(value);
            }}
          >
            <SvgIcon icon="ic_rj_plus" size="16" />
            <div className="text-text-3">添加应用</div>
          </div>
        ) : (
          <ModalsBoxContent
            className={`flex max-h-[350px] min-h-[176px] flex-col gap-3 ${tablesValue.length > 0 ? ' overflow-y-auto' : ''
              }`}
          >
            <ConfigProvider
              theme={{
                components: {
                  Table: {
                    borderColor: 'transparent',
                  },
                },
              }}
            >
              <Table
                rowClassName="cursor-pointer api-table"
                rowKey="appId"
                className="common-scrollbar"
                columns={columns}
                dataSource={tablesValue}
                pagination={false}
              />
            </ConfigProvider>
          </ModalsBoxContent>
        )}
      </Modals>
    );
  },
);

export default index;
